﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Metadata.Edm;
using System.Linq;

namespace DG.Common.EF.Reflection
{
    public class EntityEdmInfos
    {

        public IEnumerable<EdmMember> Keys { get; private set; }
        public IEnumerable<EdmMember> AutoIncrementProperties { get; private set; }
        public IEnumerable<KeyValuePair<NavigationProperty, EdmProperty[]>> FKeys { get; private set; }
        public IEnumerable<EdmMember> DataMembers { get; private set; }
        public IEnumerable<EdmProperty> PrimitiveProperties { get; private set; }

        public EntityEdmInfos(EntityType e)
        {
            Keys = e.KeyMembers;
            AutoIncrementProperties = e.Properties.Where(p => p.MetadataProperties.Any(m => m.PropertyKind == PropertyKind.Extended && Convert.ToString(m.Value) == "Identity")).ToArray();
            PrimitiveProperties = e.Properties;
            DataMembers = e.Members;

            var nav = e.NavigationProperties.Where(n => ((AssociationType)n.RelationshipType).ReferentialConstraints.Count == 1);

            FKeys = (from n in nav
                let refConst = ((AssociationType)n.RelationshipType).ReferentialConstraints.Single()
                where refConst.ToRole.GetEntityType() == e
                select new KeyValuePair<NavigationProperty, EdmProperty[]>(n, refConst.ToProperties.ToArray())).ToArray();

        }
    }
}